import { Navigate, useLocation, useRoutes } from "react-router-dom";
import Layout from "../page/Layout";
import Login from "../page/Login";
import { useEffect, useState } from "react";
import state from "../model/routerStore";
import Dashboard from "../page/Dashboard";
import Person from "../page/Person";
import Article from "../page/Article";
import Comment from "../page/Comment";
import Like from "../page/Like";

function router() {
  const location = useLocation();
  const { isAuthenticated } = state;
  // const [isAuthenticated, setIsAuthenticated] = useState(false);

  useEffect(() => {
    // 拦截路由，例如检查认证状态
    if (!isAuthenticated && location.pathname !== "/login") {
      // 如果用户未认证，重定向到登录页面
      // 你可以在这里执行任何认证失败的逻辑
      route = <Navigate to="/login" replace />;
    }
  }, [isAuthenticated, location]);

  let route = useRoutes([
    {
      path: "/",
      element: <Layout />,
      children: [
        { path: "/", element: <Dashboard /> },
        { path: "/person", element: <Person /> },
        { path: "/article", element: <Article /> },
        { path: "/comment", element: <Comment /> },
        { path: "/like", element: <Like /> },
      ],
    },
    {
      path: "/login",
      element: <Login />,
    },
  ]);
  // 如果用户未认证，拦截并重定向到登录页面
  if (!isAuthenticated && location.pathname !== "/login") {
    route = <Navigate to="/login" replace />;
  }
  return route;
}

export default router;
